
let connection;

// 配置数据库连接
const configureConnection = (config) => {
  const mysql = require('mysql2');

  connection = mysql.createConnection(config);

  connection.connect((err) => {
    if (err) {
      console.error('Error connecting to database:', err);
      throw err;
    }
    console.log('Connected to the MySQL server.');
  });

  return connection;
};

// 封装的 MySQL 操作模块
module.exports = () => {
  return {
    // 配置数据库连接
    configureConnection,

    // 查询数据
    query: async (sql, params = []) => {
      return new Promise((resolve, reject) => {
        connection.query(sql, params, (err, results) => {
          if (err) {
            reject(err);
          } else {
            resolve(results);
          }
        });
      });
    },

    // 插入数据
    insert: async (table, data) => {
      const columns = Object.keys(data).join(', ');
      const values = Object.values(data).map(() => '?').join(', ');
      const sql = `INSERT INTO ${table} (${columns}) VALUES (${values})`;
      return module.exports.query(sql, Object.values(data));
    },

    // 更新数据
    update: async (table, data, condition) => {
      const setClause = Object.keys(data).map(key => `${key} = ?`).join(', ');
      const whereClause = Object.keys(condition).map(key => `${key} = ?`).join(' AND ');
      const sql = `UPDATE ${table} SET ${setClause} WHERE ${whereClause}`;
      const params = [...Object.values(data), ...Object.values(condition)];
      return module.exports.query(sql, params);
    },

    // 删除数据
    delete: async (table, condition) => {
      const whereClause = Object.keys(condition).map(key => `${key} = ?`).join(' AND ');
      const sql = `DELETE FROM ${table} WHERE ${whereClause}`;
      return module.exports.query(sql, Object.values(condition));
    },

    // 关闭连接
    close: async () => {
      return new Promise((resolve, reject) => {
        connection.end((err) => {
          if (err) {
            reject(err);
          } else {
            resolve();
          }
        });
      });
    }
  }
}